package com.feignfilter.backend1.feign;

import com.feignfilter.backend1.exception.BaseException;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public class ResultDealDecoder implements Decoder {
    public static final String CONTENT_KEY = "content";
    final Decoder delegate;

    public ResultDealDecoder(Decoder delegate) {
        this.delegate = delegate;
    }
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        // 判断是否返回参数是否是异常

        String resultStr = IOUtils.toString(response.body().asInputStream(), "UTF-8");
        System.out.println(resultStr);
        // 拿到返回值，进行自定义逻辑处理
        if(true) {
            throw new BaseException("this is a test run time exception");
        }
        // 回写body,因为response的流数据只能读一次，这里回写后重新生成response
        return delegate.decode(response.toBuilder().body(resultStr, StandardCharsets.UTF_8).build(), type);
    }
}
